import { ref, reactive } from 'vue'
import router from '../router'
import { ElMessage } from 'element-plus'
import { loginApi, captchaApi, logoutApi, changePasswordApi, findPasswordApi } from '../api/user'

const loginForm = reactive({
  val: {}
})
const loginRules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const logining = ref(false)
const captchaSrc = ref()
const changePasswordForm = reactive({
  val: {}
})
const changePasswordVisible = ref(false)
const logoutDialogVisible = ref(false)
const emailForm = reactive({
  val: {}
})

async function logout() {
  const { data: res } = await logoutApi()
  if (!res.success) {
    ElMessage.error(res.msg)
  }
  router.replace('/')
  ElMessage.success(res.data)
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  logoutDialogVisible.value = false
}
async function login(loginFormRef) {
  const r = await loginFormRef.validate()
  if (r) {
    logining.value = true
    const { data: res } = await loginApi({
      ...loginForm.val,
      captchaToken: localStorage.getItem('captchaToken')
    })
    if (!res.success) {
      ElMessage.error(res.msg)
    } else {
      router.replace('/index')
      ElMessage.success('登录成功')
      setTimeout(() => {
        loginForm.val = {}
      }, 2000)
      localStorage.removeItem('captchaToken')
      localStorage.setItem('user', JSON.stringify(res.data))
      localStorage.setItem('token', res.map.token)
    }
    logining.value = false
  }
}
async function refreshCode() {
  const res = await captchaApi({ width: 120, height: 40 })
  const blob = new Blob([res.data], { type: 'image/png' })
  captchaSrc.value = URL.createObjectURL(blob)
  localStorage.setItem('captchaToken', res.headers.get('captchaToken'))
}
async function changePassword() {
  const { data: res } = await changePasswordApi(changePasswordForm.val)
  if (!res.success) {
    ElMessage.error(res.msg)
    return
  }
  ElMessage.success(res.data)
  clearUser()
  changePasswordForm.val = {}
  changePasswordVisible.value = false
  router.replace('/')
}
async function findPassword() {
  const { data: res } = await findPasswordApi(emailForm.val)
  if (!res.success) {
    ElMessage.error(res.msg)
    return
  }
  ElMessage.success(res.data)
  clearUser()
  emailForm.val = {}
  router.replace('/')
}
function clearUser() {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
}
function cancelChangePassword() {
  changePasswordForm.val = {}
  changePasswordVisible.value = false
}

export const useUser = () => {
  return {
    logoutDialogVisible,
    captchaSrc,
    logining,
    loginRules,
    loginForm,
    changePasswordForm,
    emailForm,
    changePasswordVisible,
    login,
    logout,
    refreshCode,
    changePassword,
    cancelChangePassword,
    findPassword
  }
}
